package cn.com.libertymutual.production.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import cn.com.libertymutual.production.exception.UserException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


/**
 * 文件上传 下载 删除
 * 
 * @author ping.liang
 * 
 */
public class FileUtil {
	
	private static String separator = "/";
	
	/*
	 * 取得操作系统文件路径中的分割符(windows是/, 其它是\\)
	 */
	public static String getSeparator(){
		String osName = System.getProperty("os.name"); 
		if (osName == null)   
            osName = "";   
		
        if (osName.toLowerCase().indexOf("win") != -1) {   
            separator = "\\";  
        } else {  
            separator = "/";  
        }  
        
        return separator;
	}
	
	/**
	 * 文件删除
	 */
	public static void deleteFile(String filename, String filepath) {
		File fu = new File(filepath + filename);
		fu.delete();
	}

	/**
	 * upload
	 * 
	 * @param fileItem
	 * @param file
	 * @throws Exception
	 */
	public static void upload(FileItem fileItem, File file) throws Exception {
		FileInputStream is = (FileInputStream)fileItem.getInputStream();
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		OutputStream os = new FileOutputStream(file);
		steam(is, os);
	}
	/**
	 * 上传指定的ftp地址
	 * @param host ftp地址
	 * @param user ftp用户名
	 * @param pwd ftp密码
	 * @param name 文件名
	 * @param InputStream 文件流
	 */
	public static void uploadnew(String host,String user,
			String pwd, String targetPath, String name, InputStream is) throws Exception{
		FTPClient ftp = new FTPClient();
		try {
			ftp.connect(host, 21);
			ftp.login(user, pwd);
			int reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				String error = ftp.getReplyString();
				ftp.disconnect();
				throw new Exception("FTP 连接失败,错误信息:"+error+"请检查配置信息!");
			}
			if (targetPath != null) {// 验证是否有该文件夹,没有则提示！
//				if (!ftp.changeWorkingDirectory(targetPath)) {
//					throw new Exception("目标文件夹不存在,请确认文件夹!");
//				}
				//ftp.changeWorkingDirectory(targetPath);
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.storeFile(name, is);
			is.close();
			ftp.logout();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ex) {
					ex.printStackTrace();
					throw ex;
				}
			}
		}	
	}

	/**
	 * 
	 * @param is
	 * @param os
	 * @throws Exception
	 */
	public static void steam(InputStream is, OutputStream os) throws Exception {
		byte[] buffer = new byte[512];
		int length = 0;
		try {
			while ((length = is.read(buffer)) > 0) {
				os.write(buffer, 0, length);
			}
		} finally {
			os.close();
			is.close();
		}
	}
	
	public static String getSize(double I){
		DecimalFormat myFormatter = new DecimalFormat("####.#");
		String sizeStr=null;
		if (I / 1024 + 0f < 1) {

			String Size = myFormatter.format(I);
			sizeStr=(Size + "k");

		} else {

			String Size = myFormatter.format(I / 1024 + 0f);
			sizeStr=(Size + "MB");

		}
		return sizeStr;
	}
	
	/**
	 * 上传影像文件到filenet和保存数据库
	 * @param bussNo 业务号--备案号
	 * @param userCode 上传用户
	 * @param comCode 用户归属机构
	 * @param fileName 文件名称
	 * @param version 版本 默认为1
	 * @param fileSize 文件大小
	 * @param inputStream 文件数据流
	 * @return fileId filenet上文件id
	 * @throws IOException 
	 * @throws HttpException 
	 */
	public static String uploadFiles(String URL,String bussNo, String userCode, String comCode, String fileName, String version,String password,long fileSize, InputStream inputStream) throws Exception {
		//String targetUrl = IndigoServer.SAVE_EFILING_IMAGE_FILES;
		//测试环境地址：URL=http://10.132.21.29:7001/eFiling/uploader/upload.do
		PostMethod filePost = new PostMethod(URL);
		filePost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
		String fileId = "";//上传filenet的文件id
		String filenameext =fileName.substring(fileName.lastIndexOf('.'));
		Part [] parts = {new FilePart("files", new ByteArrayPartSource(fileName, inputStreamTOByte(inputStream))), new StringPart("entity.systemCode", "platform","UTF-8"), 
         new StringPart("entity.businessNo", bussNo,"UTF-8"), new StringPart("entity.property00", fileName,"UTF-8"), new StringPart("entity.operator", userCode,"UTF-8"),
		 new StringPart("entity.property01",filenameext,"UTF-8" ), new StringPart("entity.property06", comCode,"UTF-8"), new StringPart("entity.property07", version,"UTF-8"),
		 new StringPart("systemCode","platform","UTF-8"),new StringPart("password",password,"UTF-8")
		};
		filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().setSoTimeout(100000);
		int status = client.executeMethod(filePost);
		if (status == HttpStatus.SC_OK) {
			//得到返回的json格式的字符串
			String responseText = filePost.getResponseBodyAsString();
			JSONObject json = JSONObject.parseObject(responseText);
			JSONArray array = JSONArray.parseArray(json.get("list").toString());
			json = array.getJSONObject(0);
			fileId = json.getString("id");
			System.out.println("上传filenet的文件fileId = " + fileId);
		    System.out.println("上传成功");
		    
		} else {
		    System.out.println("上传失败");
		    // 上传失败
		    throw new UserException("上传文件失败！");
		}
		filePost.releaseConnection();
		return fileId;
	}
	
	/** 

     * 将InputStream转换成byte数组 

     * @param in InputStream 

     * @return byte[] 

     * @throws IOException 

     */  

private static byte[] inputStreamTOByte(InputStream inputStream) throws IOException{

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();  

        byte[] data = new byte[1024];  

        int count = -1;  

        while((count = inputStream.read(data,0,1024)) != -1)  

            outStream.write(data, 0, count);  

          

        data = null;  

        return outStream.toByteArray();  

      }   
 


}
